#!/usr/bin/env python
#coding=utf8
import time

'''
by qinchuan
07/10/29 version 0.01
08/04/04  for win32 use gbk encoding output
'''

class Log(object):
    def __init__(self,config,loglevel='info'):
        # default log info level
        self.loglevel = loglevel
        self.type = ['info','warning','error','fatal','debug']
        self.config = config
        # type for logs(file or stdin)
        if self.config.type == 1:
            self.doRecord = self.writeToStdin
        else:
            # initialize the log file module
            self.doRecord = self.writeToFile
            self.logpath = self.config.logpath

    def writeLog(self,value,level='info'):
        strlog = ''
        # generate the loginfo
        strlog += time.strftime('%Y-%m-%d %X')
        try:
            if self.type.index(level) < 0:
                raise
        except:
            # except
            strlog += ";error;log type error\n"
            self.doRecord(strlog)
            return
        strlog += ";" + level + ";[" + str(value) + "]\n"
        self.doRecord(strlog)
        
    def writeToFile(self,val):
        self.logfile = open(self.logpath,mode='a+')
        self.logfile.write(val)
        self.logfile.close()
        # print values even if the info has been wrote in files
        self.writeToStdin(val)
    
    def writeToStdin(self,val):
        if self.config.win:
            print val.decode('utf-8')
        else:
            print val
